
/**
 * Created by bai on 2015/7/11.
 */
var TakingAnOrder = function(){
    var dishesList={};//菜品列表
    var DISHESLIST={};//菜品列表
    var ORDERID=null;//订单id
    var TABLEID=null;//订单id
    var ORDERTOTAL=0;
    var KEYBOARDARRAY = [];//搜索菜品，数组组合
    var KEYBOARDCombinatorics = [];//搜索菜品，字母组合
    var DIANCANPARENTSNODE = $('#suborderDishesPage');
    var keyOverflowArray = "";
    /*
     * 得到cookie
     * */
    function getCookie(c_name)
    {
        if (document.cookie.length>0)
        {
            var   c_start=document.cookie.indexOf(c_name + "=");
            var   c_end=null;
            if (c_start!=-1)
            {
                c_start=c_start + c_name.length+1
                c_end=document.cookie.indexOf(";",c_start)
                if (c_end==-1) c_end=document.cookie.length
                return unescape(document.cookie.substring(c_start,c_end))
            }
        }
        return ""
    }
    /*
     * 一条菜品html
     * */
    var oneCpHtml = function(item){
        var disaledOfAddButton = "";
        var inStock ="";
        if(!item.in_stock){
            disaledOfAddButton = "none";
            inStock="（已下架）"
        }
        $(' <li>\
                            <p class="dishesName">'+item.cp_name+'<span >'+inStock+'<span></p>\
                            <p class="dishesPrice"><span>￥'+(item.price/100).toFixed(1)+'</span>/份</p>\
                            <div class="cut active" data-functionb="btn_cp_subtractOne" data-parent="'+item.group_id+'" style="display: none" data-id="'+item.id+'"></div>\
                            <h6 class="cpNumber '+item.id+'" style="display: none">0</h6>\
                            <a class="add " style="display: '+disaledOfAddButton+'" data-functionb="btn_cp_addOne" data-parent="'+item.group_id+'" data-id="'+item.id+'" ></a>\
                            </li>').appendTo('ul.'+item.group_id);
    }
    /*
     * 菜品列表
     * */
    var showDishes = function(fun,orderId,tableId){
        if(orderId){
            ORDERID=orderId;
            TABLEID=tableId;
        }
        ORDERTOTAL=0;
        var dishPage = $('#suborderDishesPage')
        //去掉点菜的购物车的蒙布
        $('.IndexPage',dishPage).hide();
        $('.btmShoppingCarHidden',dishPage).removeClass('btmShoppingCarShow')
        $('.shoppingCarIcoWhite',dishPage).removeClass('active');
        $('.btmTrueGray',dishPage).addClass('disabled');
        $('.btmTrueGray',dishPage).removeClass('active');
        $('.keysIcoWhite',dishPage).removeClass('active');
        $('.barAndKeysDown',dishPage).removeClass('barAndKeysUp');
        //$('.searchText',DIANCANPARENTSNODE).html("菜品名称/菜品名称简码");
        $('.sbDiv',DIANCANPARENTSNODE).html('');
        $('<p class="option remind" data-function="btn_seek_cp">菜品名称/菜品名称简码</p>').appendTo('.sbDiv',DIANCANPARENTSNODE);
        //alert(ORDERID+"  "+TABLEID)
        OrderingSystem.getCpGroupList(function(data){
            $('.dishesClassList').html('');
            $('.dishesMenuList').html('');
            $('.cpPageFooterFatherNode .billCount').html('0份');
            $('.ul-ShoppingCartCpList').html('');
            dishesList={};
            KEYBOARDARRAY = [];
            keyOverflowArray = "";
            $.each(data.data,function(k,v){
                dishesList[v.id]=[];
                if(v.id!=0){
                    $('<li class="'+v.id+'" data-id="'+ v.id+'">\
                        <p>'+ v.group_name+'</p>\
                        <div class="cpSelectedNumber">0</div>\
                        </li>').appendTo('.dishesClassList')
                    /*  $('<li class="left_list" data-id="'+ v.id+'">\
                     <div class="left_ico"></div>\
                     <div class="left_sub">\
                     <p class="left_title">'+ v.group_name+'</p>\
                     </div>\
                     </li>').appendTo('.dishesClassList')*/
                }
            })
            $.each(data.data,function(k,v){
                if(v.id==0){
                    $('<li class="'+v.id+'" data-id="'+ v.id+'">\
                        <p>其他</p>\
                        <div class="cpSelectedNumber ">0</div>\
                        </li>').appendTo('.dishesClassList')
                    /* $('<li class="left_list" data-id="'+ v.id+'">\
                     <div class="left_ico"></div>\
                     <div class="left_sub">\
                     <p class="left_title" >其他</p>\
                     </div>\
                     </li>').appendTo('.dishesClassList')*/
                }
            })
            $('.dishesClassList').find('li').eq(0).addClass('active')
            OrderingSystem.getRestaurantCpList(function(data){
                fun();
                $.each(data.data,function(kCp,vCp){
                    console.log("dishesList",dishesList);
                    if( dishesList[vCp.group_id]){
                        dishesList[vCp.group_id].push(vCp);
                    }else{
                        dishesList[0].push(vCp);
                    }


                })
                console.log(dishesList)
                $.each(dishesList,function(kDish,vDish){
                    //console.error(vDish)
                    //alert(vDish[0].group_id)
                    if(vDish[0]){//判断分组下有菜
                        //alert(kDish)
                        if(kDish!=0){
                            $('<ul class="'+vDish[0].group_id+'"></ul>').appendTo('.dishesMenuList');
                            //$('<ul class="right_menu  '+vDish[0].group_id+'"></ul>').appendTo('.dishesMenuList');
                            $('<li class="menuListTitle" data-id="'+vDish[0].group_id+'"> '+vDish[0].group_name+' </li>').appendTo('.dishesMenuList .'+vDish[0].group_id);
                            console.log(vDish)
                            $.each(vDish,function(index,item){
                                console.log(item.cp_name)
                                oneCpHtml(item)
                                /*     $(' <li>\
                                 <p class="dishesName">'+item.cp_name+'</p>\
                                 <p class="dishesPrice"><span>￥'+(item.price/100).toFixed(1)+'</span>/份</p>\
                                 <div class="cut active" data-functionb="btn_cp_subtractOne" data-parent="'+item.group_id+'" style="display: none" data-id="'+item.id+'"></div>\
                                 <h6 class="cpNumber '+item.id+'" style="display: none">0</h6>\
                                 <a class="add "  data-functionb="btn_cp_addOne" data-parent="'+item.group_id+'" data-id="'+item.id+'"></a>\
                                 </li>').appendTo('ul.'+item.group_id);*/
                                /*  $('<li class="ppl_list">\
                                 <p class="ppl_name">'+item.cp_name+'</p>\
                                 <p class="ppl_price">'+(item.price/100).toFixed(1)+'/份</p>\
                                 <div class="add addActive" data-function="addCpFuntion" data-id="'+item.id+'"></div>\
                                 <h6 style="display: none">0</h6>\
                                 <div class="cut" style="display: none" data-function="minusCpFuntion" data-id="'+item.id+'"></div>\
                                 </li>').appendTo('ul.'+item.group_id);*/
                            })
                        }
                    }


                })
                console.log('dishesList',dishesList)
                $.each(dishesList,function(kDish,vDish){
                    if(vDish[0]){
                        if(kDish==0){
                            $('<ul class="'+vDish[0].group_id+'"></ul>').appendTo('.dishesMenuList');
                            //$('<ul class="right_menu  '+vDish[0].group_id+'"></ul>').appendTo('.dishesMenuList');
                            $('<li class="menuListTitle">其他 </li>').appendTo('.dishesMenuList .'+vDish[0].group_id);
                            console.log(vDish)
                            $.each(vDish,function(index,item){
                                console.log(item.cp_name)
                                oneCpHtml(item);
                                /* $(' <li>\
                                 <p class="dishesName">'+item.cp_name+'</p>\
                                 <p class="dishesPrice"><span>￥'+(item.price/100).toFixed(1)+'</span>/份</p>\
                                 <div class="cut active" data-functionb="btn_cp_subtractOne" data-parent="'+item.group_id+'" data-id="'+item.id+'" style="display: none"></div>\
                                 <h6 class="cpNumber '+item.id+'" style="display: none">0</h6>\
                                 <div class="add "  data-functionb="btn_cp_addOne" data-parent="'+item.group_id+'" data-id="'+item.id+'"></div>\
                                 </li>').appendTo('ul.'+item.group_id);*/
                                /*  $('<li class="ppl_list">\
                                 <p class="ppl_name">'+item.cp_name+'</p>\
                                 <p class="ppl_price">'+(item.price/100).toFixed(1)+'/份</p>\
                                 <div class="add addActive" data-function="addCpFuntion" data-id="'+item.id+'"></div>\
                                 <h6 style="display: none">0</h6>\
                                 <div class="cut" style="display: none" data-function="minusCpFuntion" data-id="'+item.id+'"></div>\
                                 </li>').appendTo('ul.'+item.group_id);*/
                            })
                        }
                    }


                })
                var list=$('.dishesMenuList')
                $('.dishesClassList').on('click', function (ev) {//点击分类切换菜单
                    //alert($('.dishesClassList').scrollTop())
                    if($(document).scrollTop()>100){

                    }else{
                        $('.dishesClassList').find('.active').removeClass('active')
                        $(ev.target).parents('li').addClass('active')

                        //TODO:RESEARCH?????
                        if(list != undefined){
                            //alert($(ev.target).closest('.left_list').data('id'))
                            list.scrollTop((list.scrollTop()) + (list.find('.'+$(ev.target).closest('li').data('id')).position().top));
                        }
                    }


                })
                //var menuShow=null;
                //list.on('scroll',function(){
                //    $(list.find('ul')).each(function(k,v){
                //        //alert( $('li',v).eq(0).html()+$('li',v).eq(0).position().top)
                //
                //
                //        if($('li',v).eq(0).position().top<=0){
                //            menuShow=$('li',v).eq(0).data('id');
                //        }
                //    })
                //    $(list.find('ul')).each(function(k,v){
                //        //alert( $('li',v).eq(0).html()+$('li',v).eq(0).position().top)
                //
                //
                //        if($('li',v).eq(0).position().top<=0){
                //            $('.dishesClassList').find('.active').removeClass('active');
                //            $('.dishesClassList').find('.'+menuShow).addClass('active')
                //        }
                //    })
                //
                ///*    var title = list.find('ul');
                //    for(var i=0;i<title.length;i++){
                //        if(title.eq(i).position().top>0){
                //
                //            $('.dishesClassList').find('active').removeClass('active');
                //            $('.dishesClassList').find(title.eq(i-1)).addClass('active');
                //            break;
                //        };
                //    };*/
                //
                //});
            })
        })

    }
    /*
     * 更新菜品
     * TODO://暂时无法封装
     * */
    var updateCp = function(list){
        $('.ul-ShoppingCartCpList').html('');
        $.each(dishesList,function(k,v){
            console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].count  >0){
                    $('<li>\
                         <p class="dishesName">'+v[i].cp_name+'</p>\
                         <div class="cutIco"></div>\
                         <p class="dishesCount">'+v[i].count+'份</p>\
                     <div class="addIco"></div>\
                     <p class="dishesSum">'+v[i].price+'元</p>\
                     </li>').appendTo('.ul-ShoppingCartCpList')

                }

            }
        })
    }
    /*
     * 更新菜品内存
     * */
    var updateCpObject= function(cpId,counter){
        $.each(dishesList,function(k,v){
            //console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].id == cpId){
                    v[i].count=counter;
                    console.log("cplineCount",v[i],v[i].count,counter);
                }

            }
        })
    }
    /*
     * 更新购物车里的数据
     * */
    var updateShoppingCartCpData = function(){
        //更新购物车里的数据
        $('.ul-ShoppingCartCpList').html('');
        $.each(dishesList,function(k,v){
            console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].count  >0){
                    $('<li>\
                         <p class="dishesName">'+v[i].cp_name+'</p>\
                         <div class="cutIco" data-function="btn_shoppingCutCp" data-parent="'+v[i].group_id+'" data-id="'+v[i].id+'"></div>\
                         <p class="dishesCount" >'+v[i].count+'份</p>\
                     <div class="addIco " data-function="btn_shoppingAddCp" data-parent="'+v[i].group_id+'" data-id="'+v[i].id+'"></div>\
                     <p class="dishesSum" >￥'+v[i].price/100*v[i].count+'</p>\
                     </li>').appendTo('.ul-ShoppingCartCpList')

                }

            }
        })
    }
    /*
     * 改变左侧菜品列表里小圆圈里点菜数量的数字
     * */
    var changeCpNumberOfLeftCpVarietyList= function(obj){
        var count=0;
        $('#suborderDishesPage .dishesMenuList .'+obj.data('parent')+' .cpNumber').each(function(k,v){

            count=count+Number($(v).html());
        })

        $('#suborderDishesPage .dishesClassList .'+obj.data('parent')+' .cpSelectedNumber').html(count);
    }
    /*
     * 菜品的加减按钮
     * */
    var setTempLineItem = function(obj,counter,cpTotalNumber){

        if(cpTotalNumber>0){
            $('.cpPageFooterFatherNode .btmTrueGray').addClass('active');
            $('.cpPageFooterFatherNode .btmTrueGray').removeClass('disabled');
        }else{
            $('.cpPageFooterFatherNode .btmTrueGray').removeClass('active');
            $('.cpPageFooterFatherNode .btmTrueGray').addClass('disabled');

        }
        //console.error( $('#suborderDishesPage .dishesMenuList .'+obj.data('parent')+' .cpNumber'))

        var cpId=obj.data('id')
        if(counter==0){
            obj.siblings('.cpNumber').hide();
            obj.hide();
            obj.siblings('.add').removeClass('active')
            obj.siblings('.dishesName').removeClass('active');
            $('.cpPageFooterFatherNode').find('.btmTrue').removeClass('active');
            obj.siblings('.cpNumber').html(counter);
        }else{
            obj.siblings('.cpNumber').show();
            obj.siblings('.cut').show();
            obj.siblings('.cpNumber').html(counter);
            obj.siblings('.dishesName').addClass('active');
            obj.addClass('active');
            $('.cpPageFooterFatherNode').find('.btmTrue').addClass('active');

        }
        changeCpNumberOfLeftCpVarietyList(obj);//改变菜品左侧菜品种类列表里的菜
        updateCpObject(cpId,counter);
        //更新购物车里的菜品
        updateShoppingCartCpData();
        /*  $('.ul-ShoppingCartCpList').html('');
         $.each(dishesList,function(k,v){
         console.log("cp",v);
         for(var i=0;i<v.length;i++){
         if(v[i].count  >0){
         $('<li>\
         <p class="dishesName">'+v[i].cp_name+'</p>\
         <div class="cutIco" data-function="btn_shoppingCutCp"  data-id="'+v[i].id+'"></div>\
         <p class="dishesCount" >'+v[i].count+'份</p>\
         <div class="addIco " data-function="btn_shoppingAddCp"  data-id="'+v[i].id+'"></div>\
         <p class="dishesSum" >'+v[i].price/100+'元</p>\
         </li>').appendTo('.ul-ShoppingCartCpList')

         }

         }
         })*/
    }
    /*
     * 蒙布显示
     * */
    var mengbuShow = function(){
        $('.main-page[style="dispaly:block"] .IndexPage').show();
    }
    /*
     * 蒙布隐藏
     * */
    var mengbuHide = function(){
        $('.main-page[style="dispaly:block"] .IndexPage').hide();
    }
    /*
     * 点击购物车
     * */
    var shoppingCart = function(){
        //$('.ul-ShoppingCartCpList').html('');
        $('.cpPageFooterFatherNode .barAndKeysDown').removeClass('barAndKeysUp');
        $('.cpPageFooterFatherNode .keysIcoWhite').removeClass('active');
        if($('.btmShoppingCarHidden').hasClass('btmShoppingCarShow')){
            $('.btmShoppingCarHidden').removeClass('btmShoppingCarShow');
            $('.cpPageFooterFatherNode .shoppingCarIcoWhite').removeClass('active')
            $('#suborderDishesPage .IndexPage').hide();
        }else{
            $('.btmShoppingCarHidden').addClass('btmShoppingCarShow');
            $('.cpPageFooterFatherNode .shoppingCarIcoWhite').addClass('active');
            $('#suborderDishesPage .IndexPage').show();

        }

        /*  $.each(dishesList,function(k,v){
         console.log("cp",v);
         for(var i=0;i<v.length;i++){
         if(v[i].count  >0){
         $('<li>\
         <p class="dishesName">'+v[i].cp_name+'</p>\
         <div class="cutIco"></div>\
         <p class="dishesCount">'+v[i].count+'份</p>\
         <div class="addIco"></div>\
         <p class="dishesSum">'+v[i].price+'元</p>\
         </li>').appendTo('.ul-ShoppingCartCpList')

         }

         }
         })*/
    }
    /*
     * 改变后面每条菜的加减后的总价
     * */
    var changeOneCpTotalPrice  = function(obj,cpId,counter){
        $.each(dishesList,function(k,v){
            //console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].id == cpId){
                    obj.siblings('.dishesSum').html("￥"+counter*v[i].price/100);
                    obj.siblings('.dishesPrice').html("￥"+counter*v[i].price/100);

                }

            }
        })
    }
    /*
     * 购物车里的菜品操作
     * */
    var shoppingCartSetTempLineItem = function(obj,counter,cpTotalNumber){
        var cpId=obj.data('id');
        if(cpTotalNumber>0){
            $('.cpPageFooterFatherNode .btmTrueGray').addClass('active');
            $('.cpPageFooterFatherNode .btmTrueGray').removeClass('disabled');
        }else{
            $('.cpPageFooterFatherNode .btmTrueGray').removeClass('active');
            $('.cpPageFooterFatherNode .btmTrueGray').addClass('disabled');
        }
        if(counter==0){
            obj.parents('li').remove();
            $('.dishesMenuList .cpNumber.'+cpId).siblings('.cut').hide();
            $('.dishesMenuList .cpNumber.'+cpId).siblings('.dishesName').removeClass('active');
            $('.dishesMenuList .cpNumber.'+cpId).hide();
            $('.dishesMenuList .cpNumber.'+cpId).siblings('.add').removeClass('active');
            $('.dishesMenuList .cpNumber.'+cpId).html(counter);
        }else{

            obj.siblings('.dishesCount').html(counter+"份");
            changeOneCpTotalPrice(obj,cpId,counter)//改变每条菜后面菜的总价

            $('.dishesMenuList .cpNumber.'+cpId).html(counter);


        }
        changeCpNumberOfLeftCpVarietyList(obj);
        updateCpObject(cpId,counter);
    }
    /*
     * 点菜页面，确认按钮
     * */
    var cpListOk = function(fun){

        $('#subOrderDetailsPage .ul-cpListOrderInfo').html('');
        $('#subOrderDetailsPage .specialDemand').val('');
        fun();
        var total=0;
        $.each(dishesList,function(k,v){
            console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].count  >0){
                    total+=v[i].price/100*v[i].count
                    $('    <li class="dishesInfo" >\
                        <!-- 已订菜名-->\
                        <p class="dishesName">'+v[i].cp_name+'</p>\
                        <!-- 单列已订菜品数量减-->\
                        <div class="cutIco" data-functionb="btn_shoppingOrderInfoCutCp" data-id="'+v[i].id+'" data-parent="'+v[i].group_id+'"></div>\
                        <!-- 单列已订菜品数量-->\
                        <h6 class="dishesCount" >'+v[i].count+'</h6>\
                        <!-- 单列已订菜品数量加-->\
                        <div class="addIco" data-functionb="btn_shoppingOrderInfoAddCp" data-parent="'+v[i].group_id+'" data-id="'+v[i].id+'"></div>\
                        <!-- 单列已订菜品价格-->\
                        <p class="dishesPrice">￥'+v[i].price/100*v[i].count+'</p>\
                        </li>').appendTo('.ul-cpListOrderInfo');
                    /* $('<li>\
                     <p class="dishesName">'+v[i].cp_name+'</p>\
                     <div class="cutIco" data-function="btn_shoppingCutCp" data-id="'+v[i].id+'"></div>\
                     <p class="dishesCount" >'+v[i].count+'份</p>\
                     <div class="addIco " data-function="btn_shoppingAddCp"  data-id="'+v[i].id+'"></div>\
                     <p class="dishesSum" >'+v[i].price/100+'元</p>\
                     </li>').appendTo('.ul-ShoppingCartCpList')*/

                }

            }
        })

        if(ORDERID){
            var oId = ORDERID;
            OrderingSystem.getOrderById(oId, function (data) {
                ORDERTOTAL=data.data[0].total/100;
                $('#subOrderDetailsPage .sumPrice').html("合计：￥"+Number(ORDERTOTAL+total));
                if(data.data[0].itemList[0]){
                    $('<li class="title">之前点餐明细</li>').appendTo('.ul-cpListOrderInfo');
                    $.each(data.data[0].itemList, function (k, v) {
                        $('<li class="preOrder">\
                            <p class="name">'+v.name+'</p>\
                            <p class="count">'+v.count+'份</p>\
                            <p class="price">￥'+v.price/100+'</p>\
                        </li>').appendTo('.ul-cpListOrderInfo');
                    })
                }
            });
        }else{
            $('#subOrderDetailsPage .sumPrice').html("合计：￥"+Number(ORDERTOTAL+total));
        }
    }
    /*
     * 计算菜品总价
     * */
    var calculateCpListTotal = function(){
        var total=0;
        $.each(dishesList,function(k,v){
            console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].count  >0){
                    total+=v[i].price/100*v[i].count
                }
            }
        })
        return total
    }
    /*
     * 订单详情里的的菜品操作
     * */
    var shoppingOrderCartSetTempLineItem = function(obj,counter,cpTotalNumber){

        var cpId=obj.data('id');
        if(cpTotalNumber>0){
            $('.cpPageFooterFatherNode .btmTrueGray').addClass('active');
            $('.cpPageFooterFatherNode .btmTrueGray').removeClass('disabled');
        }else{
            $('.cpPageFooterFatherNode .btmTrueGray').removeClass('active');
            $('.cpPageFooterFatherNode .btmTrueGray').addClass('disabled');
        }
        if(counter==0){
            obj.parents('li').remove();
            $('.dishesMenuList .cpNumber.'+cpId).siblings('.cut').hide();
            $('.dishesMenuList .cpNumber.'+cpId).siblings('.dishesName').removeClass('active');
            $('.dishesMenuList .cpNumber.'+cpId).hide();
            $('.dishesMenuList .cpNumber.'+cpId).siblings('.add').removeClass('active');
            $('.dishesMenuList .cpNumber.'+cpId).html(counter);
        }else{

            obj.siblings('.dishesCount').html(counter);
            changeOneCpTotalPrice(obj,cpId,counter)//改变每条菜后面菜的总价
            $('.dishesMenuList .cpNumber.'+cpId).html(counter);

        }
        changeCpNumberOfLeftCpVarietyList(obj);
        updateCpObject(cpId,counter);
        //更新购物车里的数据
        updateShoppingCartCpData();
        $('#subOrderDetailsPage .sumPrice').html('合计：￥'+(ORDERTOTAL+calculateCpListTotal()));
        /*      $('.ul-ShoppingCartCpList').html('');
         $.each(dishesList,function(k,v){
         console.log("cp",v);
         for(var i=0;i<v.length;i++){
         if(v[i].count  >0){
         $('<li>\
         <p class="dishesName">'+v[i].cp_name+'</p>\
         <div class="cutIco" data-function="btn_shoppingCutCp" data-id="'+v[i].id+'"></div>\
         <p class="dishesCount" >'+v[i].count+'份</p>\
         <div class="addIco " data-function="btn_shoppingAddCp"  data-id="'+v[i].id+'"></div>\
         <p class="dishesSum" >'+v[i].price/100+'元</p>\
         </li>').appendTo('.ul-ShoppingCartCpList')

         }

         }
         })*/
    }
    /*
     * 预定与外卖的菜品订单详情
     * */
    var reserveOrTakeOutCpOk = function(fun){
        //预定与外卖的菜品订单详情
        $('.addReserveOrTakeOutCpOrderInfo').html('');
        $('#submenuPage .specialDemand').val('');
        /*     $(' <dl class="demand">\
         <p class="demandInfo">特殊需求：</p>\
         <div class="demandDetail">可乐加冰</div>\
         </dl>').appendTo('.addReserveOrTakeOutCpOrderInfo')*/

        $.each(dishesList,function(k,v){
            console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].count  >0){
                    $('    <dl class="menuList">\
                        <p class="dishesName">'+v[i].cp_name+'</p>\
                        <p class="price">￥'+v[i].price/100+'</p>\
                        <p class="count">X'+v[i].count+'</p>\
                        </dl>').appendTo('.addReserveOrTakeOutCpOrderInfo')


                }

            }
        })
        fun();
    }
    /*
     * 菜品显示在添加预定或者的列表里
     * */
    var cpShowAddReserveOrTakeOut = function(fun){
        var takeOutParents = $('#subtakeoutOrderPage');
        var reserveParents = $('#subaddOrderPage');
        $('.contDishes .dishes',takeOutParents).html('菜品：');
        $(' .contDishes .dishes',reserveParents).html('菜品：');
        $('.demand',takeOutParents).html('特殊需求：'+  $.trim($('#submenuPage .specialDemand').val()));
        $('.demand',reserveParents).html('特殊需求：'+  $.trim($('#submenuPage .specialDemand').val()));
        $.each(dishesList,function(k,v){
            console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].count  >0){
                    $('.contDishes .dishes',takeOutParents).append(v[i].cp_name+" ");
                    $(' .contDishes .dishes',reserveParents).append(v[i].cp_name+" ");


                }

            }
        })
        fun();
    }
    /*
     * 菜品到添加预定或者添加外卖订单里
     * */
    var cpAddReserveOrTakeOutOrder = function(id,fun){
        //alert(id)
        var cpList = [];
        var oneCp = {};
        $.each(dishesList,function(k,v){
            console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].count  >0){

                    oneCp.cp_id=v[i].id;
                    oneCp.count=v[i].count;
                    //alert(v[i].id+"、、"+  oneCp.cp_id)

                    cpList.push(oneCp);
                    oneCp={}
                    //console.log(cpList)
                }

            }
        })
        var oId = id;
        var lineItemArray = cpList;
        OrderingSystem.addLineItem(oId, lineItemArray, function (data) {
            dishesList={};
            if(fun){
                fun();
            }
        });
    }
    /*
     * 判断是否打印
     * */
    var judgePrint = function(oId){
        var boolPrint = $('.okCheckBoxCpPrinter').is(":checked");
        if(boolPrint) {
            OrderingSystem.orderLineItemPrinter(oId, function (data) {

            });
        }
    }
    /*
     * 菜品列表订单确认按钮
     * */
    var cpListOrderInfoOk = function(obj,fun){
        fun();
        if(ORDERID){
            var cpList = [];
            var oneCp = {};
            $.each(dishesList,function(k,v){
                console.log("cp",v);
                for(var i=0;i<v.length;i++){
                    if(v[i].count  >0){

                        oneCp.cp_id=v[i].id;
                        oneCp.count=v[i].count;
                        //alert(v[i].id+"、、"+  oneCp.cp_id)

                        cpList.push(oneCp);
                        oneCp={}
                        //console.log(cpList)
                    }

                }
            })
            var oId = ORDERID;
            var lineItemArray = cpList;
            OrderingSystem.addLineItem(oId, lineItemArray, function (data) {
                judgePrint(oId);
                /* if(boolPrint) {
                 OrderingSystem.orderLineItemPrinter(oId, function (data) {

                 });
                 }*/

                dishesList={};
                ORDERID=null;
                TABLEID=null;
            });
            var optionsO = {};
            optionsO.orderId = oId;
            optionsO.commonRequest = [];
            optionsO.specialRequest = $.trim($('#subOrderDetailsPage .specialDemand').val());

            optionsO.successFunction = function (data) {

            };
            OrderingSystem.setOrderRequest(optionsO);//设置口味
        }


    }
    /*
     *今日订单 预定订单菜，
     * */
    var todayOrderReserveAddCpList = function(fun){
        var parentsNode = $('#subtureTakeOneSeatPage');
        $('.noOrderAndNoPay',parentsNode).hide();
        $('.orderAndPay',parentsNode).show();
        var sumMoney = 0;
        $.each(dishesList,function(k,v){
            console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].count  >0){
                    $('<p class="dish">'+v[i].cp_name+'（'+v[i].count+'）</p>').appendTo("#subtureTakeOneSeatPage .cont .orderAndPay .yeah");
                    sumMoney+=v[i].count*v[i].price
                }

            }

        })
        $('.sumInfo .money',parentsNode).html("￥"+sumMoney/100);

        fun();

    }
    /*
     * 点完菜,弹出是否落桌的提示框
     * */
    var chooseCpOrderingFoodCpInfoOk = function(obj,fun){
        $('#subOrderDetailsPage .IndexPage').show();
        $('#subOrderDetailsPage .goToTable').show();

    }
    /*
     * 选菜后落桌ok
     * */
    var chooseCpToTable = function(obj,fun){
        $('#subOrderDetailsPage .IndexPage').hide();
        $('#subOrderDetailsPage .goToTable').hide();
        OrderingSystem.getTableList(function (data) {
            fun();
            $('.chooseSeatIndexPage').hide();
            $('.chooseSeatIndexMain').hide();
            var capital = ['','壹','贰','叁','肆','伍','陆','柒','捌','玖','拾']
            $('#suborderingFoodchooseSeatPage .ul-table-list').html('');
            $('<div class="listTitle">\
                <h2>餐台列表</h2>\
                </div>').appendTo('#suborderingFoodchooseSeatPage .ul-table-list')
            $.each(data.data,function(k,v){
                if(v.tableStatus=="OPEN"){
                    var number=(v.tableCap<11)?capital[v.tableCap]:"拾";
                    $('<li data-function="btn_orderingFood_tableList_directlyClickCpTable" data-id="'+v.id+'">\
                   <div data-function="btn_orderingFood_tableList_directlyClickCpTable" data-id="'+v.id+'">'+number+'</div>\
                   <p data-function="btn_orderingFood_tableList_directlyClickCpTable" data-id="'+v.id+'">'+v.label+'（空） '+v.tableClassName+'</p>\
                   </li>').appendTo('#suborderingFoodchooseSeatPage .ul-table-list');
                }

            })
        });

    }

    /*
     * 选择桌台落桌
     * */
    var chooseTableLuoZhuo = function(obj,fun){
        var cpList = [];
        var oneCp = {};
        $.each(dishesList,function(k,v){
            console.log("cp",v);
            for(var i=0;i<v.length;i++){
                if(v[i].count  >0){

                    oneCp.cp_id=v[i].id;
                    oneCp.count=v[i].count;
                    //alert(v[i].id+"、、"+  oneCp.cp_id)

                    cpList.push(oneCp);
                    oneCp={}
                    //console.log(cpList)
                }

            }
        })
        //var pId = getCookie('bqcuser_PIN');
        var pId = localStorage.getItem('bqcuser_PIN');
        var tId = obj.data('id');
        var personCount = '4';

        var itemList =cpList;

        OrderingSystem.createOrder(pId, tId, personCount, itemList, function (data) {
            dishesList={};
            var oId = data.data[0].id;
            fun();
            //判断是否写了订单的特殊需求
            if($.trim($('#subOrderDetailsPage .specialDemand').val())==""){
                //打印菜品
                judgePrint(oId);
                /*    OrderingSystem.orderLineItemPrinter(oId, function (data) {

                 });*/
            }else{

                var options = {};
                options.orderId = data.data[0].id;
                options.commonRequest = [];
                options.specialRequest = $.trim($('#subOrderDetailsPage .specialDemand').val());

                options.successFunction = function (data) {
                    //打印菜品
                    judgePrint(oId);
                    /*     OrderingSystem.orderLineItemPrinter(oId, function (data) {

                     });*/
                };
                OrderingSystem.setOrderRequest(options);//设置口味
            }

        });
    };

    /*
     * 主页面上直接点餐按钮
     * */
    var directClickCpOfMianPage = function(fun){
        $('#subOrderDetailsPage .btmTrue').data('function','btn_orderingFood_directClickCp_cpListInfoOK')
        showDishes(fun);
        ORDERID=null;

    }
    /*
     * 搜索菜品
     * */
    var seekCp = function(){
        $('.cpPageFooterFatherNode .barAndKeysDown').addClass('barAndKeysUp');
        $('.cpPageFooterFatherNode .keysIcoWhite').addClass('active');
        //$('.searchText',DIANCANPARENTSNODE).html("");
        //KEYBOARDARRAY=[];

    }
    /***************操作键盘**************************/
    /*
     * 在页面上显示菜品列表
     * */
    var showCpListOnPageWhenClickKeyBoard = function(){
        var keyBoardString = KEYBOARDARRAY.join("");
        var keyBoardCombinatorics = KEYBOARDCombinatorics.join("");
        var display='none';
        var cpCount = 0;
        //$('.searchText',DIANCANPARENTSNODE).html(keyBoardString);
        $('.dishesMenuList').html('');
        $.each(dishesList,function(kDish,vDish){
            //console.error(vDish)
            //alert(vDish[0].group_id)
            if(vDish[0]){//判断分组下有菜
                if(vDish[0].group_id!=0){

                    $('<ul class="'+vDish[0].group_id+'"></ul>').appendTo('.dishesMenuList');
                    //$('<ul class="right_menu  '+vDish[0].group_id+'"></ul>').appendTo('.dishesMenuList');
                    $('<li class="menuListTitle" data-id="'+vDish[0].group_id+'"> '+vDish[0].group_name+' </li>').appendTo('.dishesMenuList .'+vDish[0].group_id);
                    console.log(vDish)
                    $.each(vDish,function(index,item){
                        var textString = new RegExp("\\b" + keyBoardString);
                        var textCombinatorics = new RegExp("\\b" + keyBoardCombinatorics);
                        if((keyBoardCombinatorics.length > 0)?textCombinatorics.test(item.searchStr.initialEncoding):textString.test(item.searchStr.sudokuEncoding)){
                            if(item.count>0){
                                cpCount = item.count;
                                display = "block";
                            }else{
                                cpCount = 0;
                                display = "none";
                            }
                            console.log(item.cp_name)
                            $(' <li>\
                            <p class="dishesName">'+item.cp_name+'</p>\
                            <p class="dishesPrice">'+(item.price/100).toFixed(1)+'元/份</p>\
                            <div class="cut active" data-functionb="btn_cp_subtractOne" data-parent="'+item.group_id+'" style="display: '+display+'" data-id="'+item.id+'"></div>\
                            <h6 class="cpNumber '+item.id+'" style="display: '+display+'">'+cpCount+'</h6>\
                            <div class="add "  data-functionb="btn_cp_addOne" data-parent="'+item.group_id+'" data-id="'+item.id+'"></div>\
                            </li>').appendTo('ul.'+item.group_id);
                        }

                        /*  $('<li class="ppl_list">\
                         <p class="ppl_name">'+item.cp_name+'</p>\
                         <p class="ppl_price">'+(item.price/100).toFixed(1)+'/份</p>\
                         <div class="add addActive" data-function="addCpFuntion" data-id="'+item.id+'"></div>\
                         <h6 style="display: none">0</h6>\
                         <div class="cut" style="display: none" data-function="minusCpFuntion" data-id="'+item.id+'"></div>\
                         </li>').appendTo('ul.'+item.group_id);*/
                    })
                }
            }


        })
        console.log('dishesList',dishesList)
        $.each(dishesList,function(kDish,vDish){
            if(vDish[0]){
                if(vDish[0].group_id==0){

                    $('<ul class="'+vDish[0].group_id+'"></ul>').appendTo('.dishesMenuList');
                    //$('<ul class="right_menu  '+vDish[0].group_id+'"></ul>').appendTo('.dishesMenuList');
                    $('<li class="menuListTitle">其他 </li>').appendTo('.dishesMenuList .'+vDish[0].group_id);
                    console.log(vDish)
                    $.each(vDish,function(index,item){
                        var textString = new RegExp("\\b" + keyBoardString);
                        var textCombinatorics = new RegExp("\\b" + keyBoardCombinatorics);
                        if((keyBoardCombinatorics.length > 0)?textCombinatorics.test(item.searchStr.initialEncoding):textString.test(item.searchStr.sudokuEncoding)){
                            console.log(item.cp_name)
                            if(item.count>0){
                                cpCount = item.count;
                                display = "block";
                            }else{
                                cpCount = 0;
                                display = "none";
                            }
                            $(' <li>\
                            <p class="dishesName">'+item.cp_name+'</p>\
                            <p class="dishesPrice">'+(item.price/100).toFixed(1)+'元/份</p>\
                            <div class="cut active" data-functionb="btn_cp_subtractOne" data-parent="'+item.group_id+'" data-id="'+item.id+'" style="display: '+display+'"></div>\
                            <h6 class="cpNumber '+item.id+'" style="display: '+display+'">'+cpCount+'</h6>\
                            <div class="add "  data-functionb="btn_cp_addOne" data-parent="'+item.group_id+'" data-id="'+item.id+'"></div>\
                            </li>').appendTo('ul.'+item.group_id);
                        }

                        /*  $('<li class="ppl_list">\
                         <p class="ppl_name">'+item.cp_name+'</p>\
                         <p class="ppl_price">'+(item.price/100).toFixed(1)+'/份</p>\
                         <div class="add addActive" data-function="addCpFuntion" data-id="'+item.id+'"></div>\
                         <h6 style="display: none">0</h6>\
                         <div class="cut" style="display: none" data-function="minusCpFuntion" data-id="'+item.id+'"></div>\
                         </li>').appendTo('ul.'+item.group_id);*/
                    })
                }
            }


        })
    }
    /*
     * 使数组加
     * */
    var keyBoardArrayAdd = function(number){
        /*KEYBOARDCombinatorics = [];
         //获取点击键盘产生的组合
         if(firstLetterArray.length > 0){
         var arr = firstLetterArray;
         firstLetterArray = [];
         $.each(arr,function(karr,varr){
         $.each(letter.split('/'),function(knumber,vnumber){
         firstLetterArray.push(varr + vnumber);
         });
         })
         }else{
         firstLetterArray = letter.split('/');
         }*/
        var a = ["","1","A","D","G","J","M","P","T","W"]
        keyOverflowArray += a[number];
        KEYBOARDCombinatorics  = [];//用来存放，点击搜索框的字母组合
        KEYBOARDARRAY.push(number);
        combinatoricsScreening(KEYBOARDARRAY);
        showCpListOnPageWhenClickKeyBoard();
    }
    /*
     * 使数组的减
     * */
    var keyBoardArraySubtract = function(){
        KEYBOARDARRAY.pop();
        /*KEYBOARDCombinatorics = [];
         if(firstLetterArray.length > 0){
         if(firstLetterArray.length > 1){
         var a = [];
         $.each(firstLetterArray,function(karr,varr){
         a.push(varr.substring(0,varr.length-1));
         })
         firstLetterArray = [];
         $.each(a,function(ka,va){
         var b = true;
         $.each(firstLetterArray,function(kf,vf){
         if(vf == va){
         b = false;
         }
         })
         if(b){
         firstLetterArray.push(va);
         }
         })
         }
         if(firstLetterArray.length == 1){
         firstLetterArray = [];
         }
         combinatoricsScreening(firstLetterArray);
         }*/
        keyOverflowArray = keyOverflowArray.substring(0,keyOverflowArray.length - 1);
        KEYBOARDCombinatorics  = [];//用来存放，点击搜索框的字母组合
        combinatoricsScreening(KEYBOARDARRAY);
        showCpListOnPageWhenClickKeyBoard();
    }
    /*
     * 点击键盘的字符
     * */
    var clickKeyBoardWord = function(){
        var parentsNode = $('#orderDishesBottomPage');
        $('.btmKeys',parentsNode).on('click',function(ev){
            if($(ev.target).data('number')){
                if($(ev.target).data('number') != "x"){
                    keyBoardArrayAdd($(ev.target).data('number'));//操作键盘上的数字
                }else if($(ev.target).data('number') == "x"){
                    //操作键盘上的X
                    keyBoardArraySubtract();
                }
            }

            //alert($(ev.target).data('number'))
        })
    }();
    /*
     * 点击搜索框里的字母组合*/
    var clickSeekCombinatorics = function(obj){
        //添加单选效果
        if(obj.hasClass("active")){
            obj.removeClass("active");
            KEYBOARDCombinatorics  = [];
        }
        else{
            $('.sbDiv',DIANCANPARENTSNODE).find('p').removeClass("active");
            obj.addClass("active");
            KEYBOARDCombinatorics  = [];
            KEYBOARDCombinatorics.push(obj.html());
        }
        showCpListOnPageWhenClickKeyBoard();
    };
    /*
     * 点击键盘上的X
     * */
    var clickKeyBoardXSubWord = function(){
        var parentsNode = $('#orderDishesBottomPage');
        $('.keysDel',parentsNode).click(function(){
            alert(1)
            KEYBOARDARRAY.pop();
            console.log(  KEYBOARDARRAY)
            keyBoardArraySubtract();
        })

    }
    /*
     * 筛选出能匹配到菜品的组合,并显示在搜索框
     * */
    var combinatoricsScreening = function(keyBoardArray){
        $('.sbDiv',DIANCANPARENTSNODE).html('');
        var keyBoardString = keyBoardArray.join("");
        var firstLetterArray = [];//临时存放首字母组合的数组（内容有重复）
        var inAdditionToMoreThan = [];//最终可以显示在页面上的组合的数组
        if(keyBoardArray.length > 0){
            //生成临时的组合数组
            $.each(dishesList,function(kDish,vDish){
                if(vDish[0]) {
                    $.each(vDish,function(index,item){
                        var text = new RegExp("\\b" + keyBoardString);
                        if(text.test(item.searchStr.sudokuEncoding)){
                            $.each(item.searchStr.initialEncoding.split('|'),function(k,v){
                                firstLetterArray.push(v.substring(0,keyBoardString.length));
                            })
                        }
                    })
                }
            })
            //除余
            $.each(firstLetterArray,function(ki,vi){
                var a = true;
                $.each(inAdditionToMoreThan,function(kf,vf){
                    if(vi == vf){
                        a = false;
                    }
                })
                if(a){
                    inAdditionToMoreThan.push(vi);
                }
            })
            //将存在的菜品缩写显示
            if(inAdditionToMoreThan.length > 0){
                keyOverflowArray = inAdditionToMoreThan[0];
                $.each(inAdditionToMoreThan,function(k,v){
                    $('<p class="option" data-function="btn_seek_combinatorics">'+v+'</p>').appendTo('.sbDiv',DIANCANPARENTSNODE);
                })
            }
            else{
                $('<p class="option remind">'+keyOverflowArray+'</p>').appendTo('.sbDiv',DIANCANPARENTSNODE);
            }
        }
        else{
            $('<p class="option remind">菜品名称/菜品名称简码</p>').appendTo('.sbDiv',DIANCANPARENTSNODE);
        }
        /*if(firstLetterArray.length > 0){
         //将可以匹配到菜的组合,加入一个数组
         var inAdditionToMoreThan = [];
         $.each(dishesList,function(kDish,vDish){
         if(vDish[0]) {//判断分组下有菜
         $.each(vDish,function(index,item){
         $.each(firstLetterArray,function(kletter,vletter){
         var text = new RegExp("\\b" + vletter);
         if(text.test(item.searchStr.initialEncoding)){
         var a = true;
         $.each(inAdditionToMoreThan,function(k,v){
         if(v == vletter){
         a = false;
         }
         })
         if(a){
         inAdditionToMoreThan.push(vletter);
         }
         }
         })
         })
         }
         })
         //将可以匹配到菜品的组合，显示到搜索框
         if(inAdditionToMoreThan.length > 0){
         $.each(inAdditionToMoreThan,function(k,v){
         $('<p class="option" data-function="btn_seek_combinatorics">'+v+'</p>').appendTo('.sbDiv',DIANCANPARENTSNODE);
         })
         }
         else{
         $('<p class="option remind">没有可以匹配到菜品的组合</p>').appendTo('.sbDiv',DIANCANPARENTSNODE);
         }
         }
         else{
         $('<p class="option remind">菜品名称/菜品名称简码</p>').appendTo('.sbDiv',DIANCANPARENTSNODE);
         }*/
    }
    return{
        seekCp:function(){
            seekCp();
        },
        clickSeekCombinatorics:function(obj){
            clickSeekCombinatorics(obj);
        },
        showDishes:function(fun,orderId,tableId){
            showDishes(fun,orderId,tableId);
        },
        setTempLineItem:function(obj,counter,cpTotalNumber){
            setTempLineItem(obj,counter,cpTotalNumber);
        },
        shoppingCart:function(){
            shoppingCart();
        },
        /*购物车菜品加按钮*/
        shoppingCartSetTempLineItem:function(obj,counter,cpTotalNumber){
            shoppingCartSetTempLineItem(obj,counter,cpTotalNumber);
        },
        cpListOk:function(fun){
            cpListOk(fun);
        },
        shoppingOrderCartSetTempLineItem:function(obj,counter,cpTotalNumber){
            shoppingOrderCartSetTempLineItem(obj,counter,cpTotalNumber);
        },
        reserveOrTakeOutCpOk:function(fun){
            reserveOrTakeOutCpOk(fun);
        },
        cpShowAddReserveOrTakeOut:function(fun){
            cpShowAddReserveOrTakeOut(fun);
        },
        cpAddReserveOrTakeOutOrder:function(id,fun){
            cpAddReserveOrTakeOutOrder(id,fun);
        },
        //菜品订单详情里的确定按钮
        cpListOrderInfoOk:function(obj,fun){
            cpListOrderInfoOk(obj,fun)
        },
        /*点完菜，去落桌*/
        chooseCpOrderingFoodCpInfoOk:function(obj,fun){
            chooseCpOrderingFoodCpInfoOk(obj,fun);
        },
        /*选择菜品落桌*/
        chooseCpToTable:function(obj,fun){
            chooseCpToTable(obj,fun);
        },
        /*选择桌台落桌*/
        chooseTableLuoZhuo:function(obj,fun){
            chooseTableLuoZhuo(obj,fun);
        },
        directClickCpOfMianPage:function(obj,fun){
            directClickCpOfMianPage(obj,fun);
        },
        /*今日订单预定订单加菜*/
        todayOrderReserveAddCpList:function(fun){
            todayOrderReserveAddCpList(fun);
        }

    }
}();